package top.lwaiting.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import top.lwaiting.pojo.Configuration;
import top.lwaiting.pojo.MappedStatement;

import java.io.InputStream;
import java.util.List;

/**
 * 解析Mapper.xml 将 sql 语句封装成 MappedStatement 对象
 * @author YANG
 * @version V1.0
 * @date 2024/1/15 18:07
 * @see XMLMapperBuilder
 **/
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 进行 Mapper.xml 文件解析，解析后的sql封装到 mappedStatement
     * @param inputStream {@link InputStream}
     * @throws DocumentException {@link Exception}
     */
    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        // select 集合
        List<Element> selectList = rootElement.selectNodes("//select");
        for (Element element : selectList) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            // 去除两端空格
            String sqlText = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sqlText);

            String namespace = rootElement.attributeValue("namespace");
            // key: namespace.id
            String key = namespace+"."+id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
